// 导入数据库操作模块
const db = require('../db/index')

// 获取职工表的处理函数
exports.getEmpList = (req, res) => {
  // const sql = `select * from sale_emp`
  let pagesize = 5
  let pagenum = (req.query.pagenum - 1)*pagesize
  const sql = `select eid,ename,area,position,state,department,(select count(1) from sale_emp) as 'total'
  from sale_dep a,sale_emp b
  where a.sid = b.sid
  ORDER BY eid ASC
	limit ${pagenum},${pagesize}`
  db.query(sql, (err, results) => {
    if(err) return res.cc(err)
    if(results.length < 0) return res.cc('获取职工信息失败！')
    res.send({
      status: 0,
      message: '获取职工信息成功！',
      data: results,
      total:results[0].total
    })
  })
}


// 根据职工名字搜索职工信息
exports.searchWorkerinfo = (req, res) => {
  const sql = `select eid,ename,area,position,state,department from sale_emp a, sale_dep b where a.sid =b.sid and ename = ?`
  db.query(sql, req.query.ename, (err, results) => {
    if(err) return res.cc(err)
    if(results.length < 0) return res.cc('查询职工信息失败！')
    res.send({
      status: 0,
      message: '查询职工信息成功！',
      data: results
    })
  })
}

// 添加职工处理函数
exports.addWorker = (req, res) => {
  let ssid = 0
  if(req.body.department === '市场部'){
    ssid = 101
  }else if(req.body.department === '策划部'){
    ssid = 102
  }else if(req.body.department === '人事部'){
    ssid = 103
  }else if(req.body.department === '技术部'){
    ssid = 104
  }else{
    ssid = 101
  }

  const sql = `insert into sale_emp set ename =? ,area =? ,position =?,state = 0, sid =${ssid} `
  db.query(sql,[req.body.ename, req.body.area, req.body.position], (err, results) => {
    if(err) return res.cc(err)
    if(results.affectedRows !== 1) return res.cc('添加职工信息失败！')
    res.cc('添加职工信息成功！',0)
  })
}

// 更具职工号删除职工信息处理函数
exports.deleteByEid = (req, res) => {
  const sql = `delete from sale_emp where eid =?`
  db.query(sql, req.params.eid, (err, results) => {
    if(err) return res.cc(err)
    if(results.affectedRows !== 1) return res.cc('删除职工信息失败！')
    res.cc('删除职工信息成功！', 0)
  })
}